package com.example.beikeyigou;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;

import androidx.annotation.NonNull;

public class BuyNumDialog extends Dialog {

    ImageView cancelIv;
    AmountView amountView;
    Button ensureBtn;
    public interface OnEnsureListener{
        public void onEnsure(int num);
    }

    OnEnsureListener onEnsureListener;

    public void setOnEnsureListener(OnEnsureListener onEnsureListener) {
        this.onEnsureListener = onEnsureListener;
    }

    public BuyNumDialog(@NonNull Context context) {
        super(context);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_buynum);
        initView();

    }

    private void initView() {
        cancelIv = findViewById(R.id.dialog_buynum_cancel);
        amountView = findViewById(R.id.dialog_buynum_amount);
        ensureBtn = findViewById(R.id.dialog_buynum_btn);

        cancelIv.setOnClickListener(onClickListener);
        ensureBtn.setOnClickListener(onClickListener);

    }


    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.dialog_buynum_cancel:
                    cancel();
                    break;

                case R.id.dialog_buynum_btn:
                    if (onEnsureListener !=null){
                        int etNum = amountView.getEtNum();
                        onEnsureListener.onEnsure(etNum);
                    }

                    break;


            }
        }
    };



    //    设置对话框宽度和屏幕宽度一致
    public void setDialogWidth(){
        Window window = getWindow();   //当前屏幕窗口对象
        WindowManager.LayoutParams wlp = window.getAttributes();  //获取窗口信息参数
        //获取屏幕宽度
        Display d = window.getWindowManager().getDefaultDisplay();
        wlp.width = (int)(d.getWidth());   //对话框窗口宽度为屏幕窗口宽度
        wlp.gravity = Gravity.BOTTOM;    //从底部弹出对话框
        window.setBackgroundDrawableResource(android.R.color.transparent);   //设置窗口背景透明
        window.setAttributes(wlp);
        //自动弹出软键盘
        handler.sendEmptyMessageDelayed(1,100);
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            InputMethodManager manager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            manager.toggleSoftInput(0,InputMethodManager.HIDE_NOT_ALWAYS);
        }
    };






}
